package com.ruoyi.partybuilding.controller;

import cn.hutool.core.util.IdUtil;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.annotation.DataScope;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.partybuilding.common.EQueryController;
import com.ruoyi.partybuilding.common.PageSort;
import com.ruoyi.partybuilding.common.TableDataInfoRows;
import com.ruoyi.partybuilding.domain.MallGoods;
import com.ruoyi.partybuilding.domain.MallOrder;
import com.ruoyi.partybuilding.domain.MallOrder;
import com.ruoyi.partybuilding.domain.MallPoints;
import com.ruoyi.partybuilding.service.impl.MallPointsServiceImpl;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.var;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Date;

@Api(tags = "商城订单")
@RestController
@RequestMapping("/partybuilding/MallOrder")
public class MallOrderController extends EQueryController<MallOrder>
{
    @Resource
    MallPointsServiceImpl mallPointsService;
    /**
     * 查询列表
     */
    @Anonymous
    @ApiOperation("列表")
    @PreAuthorize("@ss.hasPermi('partybuilding:MallOrder:query')")
    @GetMapping("/list")
    @DataScope
    public TableDataInfoRows<MallOrder> list(MallOrder entity, PageSort page) {
        return super.list(entity, page);
    }



    /**
     * 获取详细信息
     */
    @DataScope
    @ApiOperation("详情")
    @PreAuthorize("@ss.hasPermi('partybuilding:MallOrder:query')")
    @GetMapping(value = "/{id}")
    public R<MallOrder> getInfo(@PathVariable("id") Long id)
    {
        return super.getInfo(id);
    }

    /**
     * 新增
     */
    @ApiOperation("新增")
    @PreAuthorize("@ss.hasPermi('partybuilding:MallOrder:add')")
    @Log(title = "商城订单", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @DataScope
    @Transactional
    public R<Long> add(@RequestBody MallOrder entity) {
        if (entity.getGoodsId() == null || entity.getQuantity() == null || entity.getQuantity() < 0)
            return R.bad("购买信息错误");
        var userId = getUserId();
        var goods = queryHelper.queryable(MallGoods.class).whereById(entity.getGoodsId()).firstOrNull();
        var oldQua = goods.getQuantity();
        if(goods.getStatus()==null||goods.getStatus()==0)
            return R.bad("商品未上架");
        if (entity.getQuantity() > oldQua)
            return R.bad("数量不足");
        if (entity.getTotalPrice()<0||entity.getQuantity() * goods.getPrice() != entity.getTotalPrice())
            return R.bad("总价不正确");
        entity.setGoodsName(goods.getName());
        entity.setStatus(1);
        entity.setUserId(userId);
        entity.setUserNickname(getLoginUser().getUser().getNickName());
        entity.setPhonenumber(getLoginUser().getUser().getPhonenumber());
        entity.setCreateTime(new Date());
        entity.setCreateBy(getUsername());
        entity.setOrderNum("YCM"+IdUtil.getSnowflakeNextIdStr());
        //减库存
        goods.quantitySetBy(entity.getQuantity());
        queryHelper.query().updatable(goods).executeRows();
        //扣积分
        var oldPoint = mallPointsService.topPoints(userId);
        if (oldPoint==null||oldPoint.getTotal() < entity.getTotalPrice())
            return R.bad("积分不足");
        //创建订单
        var re = super.add(entity);

        var newPoint =mallPointsService.newPoints(userId,-entity.getTotalPrice(),"order:" + entity.getId(),"积分兑换");
        mallPointsService.add(newPoint);
        return re;
    }
}

